package com.loe.ktui.ui_custom

import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.core.view.isVisible
import com.loe.ktui.*
import com.loe.ktui.ui.KtFrameLayout
import com.loe.ktui.ui.UiFrameLayout
import com.loe.ktui.ui.UiGroup
import com.loe.ktui.util.UiShape

open class UiTitleView(id: String? = null) : UiFrameLayout(id)
{
    override var width: Any? = MATCH_PARENT

    var leftVisible: Boolean? = null
    var leftSrc: Any? = null
    var barHeight: Any = 45
    var barVisible: Boolean? = null
    var barBg: Any? = null
    var title: String? = null
    var titleBold: Boolean? = null
    var titleSize: Any? = null
    var titleGravity: Int? = null
    var right: String? = null
    var rightWidth: Any? = null
    var rightSrc: Any? = null
    var rightEnable: Boolean? = null
    var color: Int? = null

    var statusFull: Boolean? = null
    var statusBg: Int? = null
    var statusVisible: Boolean? = null
    var captionVisible: Boolean? = null
    var navigationVisible: Boolean? = null
    var imeVisible: Boolean? = null
    var statusLight: Boolean? = false
    var navigationLight: Boolean? = null

    open var onRightClick: (View.() -> Unit)? = null
    open fun onRightClick(onRightClick: View.() -> Unit)
    {
        this.onRightClick = onRightClick
    }

    open var delayRightClick: (View.() -> Unit)? = null
    open fun delayRightClick(delayRightClick: View.() -> Unit)
    {
        this.delayRightClick = delayRightClick
    }

    fun initUI(context: Context, view: KtTitleView)
    {
        super.initUI(context, view)

        leftVisible?.let { view.imageLeft.isVisible = it }
        leftSrc?.let {
            if (it is UiShape)
            {
                view.imageLeft.setImageDrawable(it.createDrawable())
            } else
            {
                view.imageLeft.src = it.toString()
            }
        }
        view.setBarHeight(barHeight.dist)
        barVisible?.let { view.bar.isVisible = it }
        barBg?.let {
            if (it is UiShape)
            {
                view.bar.background = it.createDrawable()
            } else if (it is Int)
            {
                view.bar.setBackgroundColor(it)
            } else
            {
                view.bar.bg = it.toString()
            }
        }
        title?.let { view.textTitle.text = it }
        titleBold?.let { view.setTitleBold(it) }
        titleSize?.let { view.setTitleSize(it.distFloat) }
        titleGravity?.let { view.setTitleGravity(it) }
        right?.let { view.setRight(it) }
        rightWidth?.let { view.setRightWidth(it.dist) }
        rightSrc?.let {
            view.textRight.isVisible = false
            view.imageRight.isVisible = true
            if (it is UiShape)
            {
                view.imageRight.setImageDrawable(it.createDrawable())
            } else
            {
                view.imageRight.src = it.toString()
            }
        }
        rightEnable?.let { view.setRightEnable(it) }
        color?.let { view.setColor(it) }
        onRightClick?.let { onClick -> view.setOnClickListener { view.onClick() } }
        delayRightClick?.let { delayClick -> view.setDelayRightListener { view.delayClick() } }

        statusFull?.let { view.statusFull = it }
        statusBg?.let { view.statusBg = it }
        statusVisible?.let { view.statusVisible = it }
        captionVisible?.let { view.captionVisible = it }
        navigationVisible?.let { view.navigationVisible = it }
        imeVisible?.let { view.imeVisible = it }
        statusLight?.let { view.statusLight = it }
        navigationLight?.let { view.navigationLight = it }
    }

    override fun createView(context: Context, parent: ViewGroup?): KtTitleView
    {
        return KtTitleView(context).also()
        {
            initUI(context, it)
            addToParent(parent, it)
        }
    }
}

fun Any.ui_TitleView(id: String? = null, block: (UiTitleView.() -> Unit)? = null): UiTitleView
{
    val ui = UiTitleView(id)
    block?.let { ui.it() }
    if (this is UiGroup) addChild(ui)
    return ui
}

class KtTitleView : KtFrameLayout
{
    constructor(context: Context) : super(context)
    {
        initXML()
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    {
        initXML(attrs)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
    {
        initXML(attrs)
    }

    private fun initXML(attrs: AttributeSet? = null)
    {
        bar = inflate(context, R.layout.kt_title_layout, null) as FrameLayout
        addView(bar)

        imageLeft = findViewById(R.id.imageLeft)
        textTitle = findViewById(R.id.textTitle)
        textRight = findViewById(R.id.textRight)
        imageRight = findViewById(R.id.imageRight)
        val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
        statusHeight = resources.getDimensionPixelSize(resourceId)
        imageLeft.setOnClickListener()
        {
            try
            {
                (context as Activity).onBackPressed()
            } catch (e: Exception)
            {
            }
        }
        bar.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom)
        setPadding(0, 0, 0, 0)
    }

    lateinit var bar: FrameLayout
        internal set

    lateinit var imageLeft: ImageView
        internal set
    lateinit var textTitle: TextView
        internal set
    lateinit var textRight: TextView
        internal set
    lateinit var imageRight: ImageView
        internal set

    var statusHeight = 0
        private set

    /**
     * 设置标题栏高度
     */
    fun setBarHeight(height: Int)
    {
        val params = bar.layoutParams as LayoutParams
        params.height = height
        bar.layoutParams = params
    }

    fun setColor(color: Int)
    {
        imageLeft.setColorFilter(color)
        textTitle.setTextColor(color)
        textRight.setTextColor(color)
        imageRight.setColorFilter(color)
    }

    /**
     * 设置标题文字粗体
     */
    fun setTitleBold(isBold: Boolean)
    {
        textTitle.typeface = if (isBold) Typeface.DEFAULT_BOLD else Typeface.DEFAULT
    }

    /**
     * 设置标题文字大小
     */
    fun setTitleSize(size: Float)
    {
        textTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, size)
    }

    /**
     * 设置标题对齐方式
     */
    fun setTitleGravity(gravity: Int)
    {
        textTitle.gravity = gravity
    }

    /**
     * 设置右边文字
     */
    fun setRight(right: String)
    {
        textRight.text = right
        if (right.isNotEmpty())
        {
            textRight.isVisible = true
            imageRight.isVisible = false
        } else
        {
            textRight.isVisible = false
        }
    }

    /**
     * 设置右边图片大小
     */
    fun setRightWidth(width: Int)
    {
        val params = imageRight.layoutParams as LayoutParams
        params.width = width
        imageRight.layoutParams = params
    }

    /**
     * 设置右边允许
     */
    fun setRightEnable(enable: Boolean)
    {
        textRight.isEnabled = enable
        textRight.alpha = if (enable) 1f else 0.65f

        imageRight.isEnabled = enable
        imageRight.alpha = if (enable) 1f else 0.65f
    }

    /**
     * 设置右边监听
     */
    fun setRightListener(onClick: (v: View) -> Unit)
    {
        textRight.setOnClickListener(onClick)
        imageRight.setOnClickListener(onClick)
    }

    /**
     * 设置右边监听
     */
    fun setDelayRightListener(onClick: (v: View) -> Unit)
    {
        textRight.setDelayClickListener(0, 1200, onClick)
        imageRight.setDelayClickListener(0, 1200, onClick)
    }

    /*************************************************** 系统栏 ************************************************/

    val windowController by lazy {
        val controller = ViewCompat.getWindowInsetsController(this)
        controller?.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
        controller
    }

    /** 状态栏、标题栏、导航栏 显示 */
    var systemBarsVisible: Boolean = false
        set(value)
        {
            field = value
            if (value)
            {
                windowController?.show(WindowInsetsCompat.Type.systemBars())
            } else
            {
                windowController?.hide(WindowInsetsCompat.Type.systemBars())
            }
        }

    /** 状态栏 背景 */
    inline var statusBg: Int
        get() = (context as Activity).window.statusBarColor
        set(value)
        {
            try
            {
                (context as Activity).window.statusBarColor = value
            } catch (e: Exception)
            {
            }
        }

    /** 状态栏 全屏 */
    var statusFull: Boolean = false
        set(value)
        {
            field = value
            try
            {
                val window = (context as Activity).window
                if (value)
                {
                    window.statusBarColor = Color.TRANSPARENT
                    window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
                    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
                    window.decorView.systemUiVisibility = SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or SYSTEM_UI_FLAG_LAYOUT_STABLE
                }else
                {
                    window.decorView.systemUiVisibility = SYSTEM_UI_FLAG_LAYOUT_STABLE
                }
                // WindowCompat.setDecorFitsSystemWindows(window, !value)
                setPadding(0, if (value) statusHeight else 0, 0, 0)
            } catch (e: Exception)
            {
            }
        }

    /** 状态栏 显示 */
    var statusVisible: Boolean = false
        set(value)
        {
            field = value
            if (value)
            {
                windowController?.show(WindowInsetsCompat.Type.statusBars())
            } else
            {
                windowController?.hide(WindowInsetsCompat.Type.statusBars())
            }
        }

    /** 标题栏 显示 */
    var captionVisible: Boolean = false
        set(value)
        {
            field = value
            if (value)
            {
                windowController?.show(WindowInsetsCompat.Type.captionBar())
            } else
            {
                windowController?.hide(WindowInsetsCompat.Type.captionBar())
            }
        }

    /** 导航栏 显示 */
    var navigationVisible: Boolean = false
        set(value)
        {
            field = value
            if (value)
            {
                windowController?.show(WindowInsetsCompat.Type.navigationBars())
            } else
            {
                windowController?.hide(WindowInsetsCompat.Type.navigationBars())
            }
        }

    /** 软键盘 显示 */
    var imeVisible: Boolean = false
        set(value)
        {
            field = value
            if (value)
            {
                windowController?.show(WindowInsetsCompat.Type.ime())
            } else
            {
                windowController?.hide(WindowInsetsCompat.Type.ime())
            }
        }

    /** 状态字体亮色 */
    var statusLight: Boolean = false
        set(value)
        {
            field = value
            windowController?.isAppearanceLightStatusBars = !value
        }

    /** 导航栏字体亮色 */
    var navigationLight: Boolean = false
        set(value)
        {
            field = value
            windowController?.isAppearanceLightNavigationBars = !value
        }
}